package com.superbug.moi.stupiccqupt.ui.fragment;


import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.gc.materialdesign.views.ButtonRectangle;
import com.superbug.moi.stupiccqupt.R;
import com.superbug.moi.stupiccqupt.service.MyService;
import com.superbug.moi.stupiccqupt.util.LogUtil;
import com.superbug.moi.stupiccqupt.util.ResponseCallbackListener;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class SearchIdFragment extends Fragment implements View.OnClickListener, ResponseCallbackListener {

    private EditText mEditText;
    private ButtonRectangle searchId;
    private TextView httpContent;
    private InputMethodManager inputMethodManager;
    private MyService.MyBinder binder;
    private MyService myService;

    /**
     * 在bind时候得到当前Service实例
     * 将fragment实现ResponseCallbackListener接口
     * 把fragment设置为当前Service的回调者
     */
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            binder = (MyService.MyBinder) service;
            myService = binder.getMyService();
            myService.setResponseCallbackListener(SearchIdFragment.this);

        }
        @Override
        public void onServiceDisconnected(ComponentName name) {}
    };

    public static final int SHOW_RESPONSE = 0;

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_RESPONSE:
                    List<Map<String, Object>> response = (List<Map<String, Object>>) msg.obj;
                    LogUtil.getInstance().d("TAG", "那是不是传过来了呢：" + response.toString());
                    // 在这里进行UI操作，将结果显示到界面上
                    httpContent.setText(responseSet(response));
            }
        }
    };

    private String responseSet(List<Map<String, Object>> response) {
        String test = "";
        for (int i = 0; i < response.size(); i++) {
            Iterator it = response.get(i).keySet().iterator();
            while (it.hasNext()) {
                String key;
                String value;
                key = it.next().toString();
                value = (String) response.get(i).get(key);
                switch (key) {
                    case "stu_id":
                        test += "学号：";
                        break;
                    case "stu_name":
                        test += "姓名：";
                        break;
                    case "stu_sex":
                        test += "性别：";
                        break;
                    case "stu_class":
                        test += "班级：";
                        break;
                    case "stu_major":
                        test += "专业：";
                        break;
                    case "stu_faculty":
                        test += "院系：";
                        break;
                    case "stu_grade":
                        test += "年级：";
                        break;
                    case "error":
                        break;
                }
                test += value;
                test += "\n";
            }
            test += "\n";
        }
        LogUtil.getInstance().d("TAG", "难道text为空么：" + test);
        return test;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_search_id, container, false);
        init(view);
        return view;
    }

    private void init(View view) {
        mEditText = (EditText) view.findViewById(R.id.ed_student_name);
        searchId = (ButtonRectangle) view.findViewById(R.id.btn_search_id);
        searchId.setOnClickListener(this);
        httpContent = (TextView) view.findViewById(R.id.tv_http_test);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_search_id:
                sendRequestWithHttpURLConnection();
                inputMethodManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
                break;
        }
    }

    private void sendRequestWithHttpURLConnection() {
        String name = mEditText.getText().toString();
        try {
            name = new String(name.getBytes("GBK"), "iso8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        LogUtil.getInstance().d("----->", name);
        // 开启线程来发起网络请求
        String address = "http://jwzx.cqupt.edu.cn/pubBjStu.php?searchKey=" + name;
        Intent service = new Intent(getActivity(), MyService.class);
        service.putExtra("address", address);
        getActivity().bindService(service, connection, Context.BIND_AUTO_CREATE);
    }

    @Override
    public void onDestroy() {
        getActivity().unbindService(connection);
        super.onDestroy();
    }

    /**
     * Service解析完http后，回调返回的信息
     * @param message 保存了学生数据的message，发给handler更新ui
     */
    @Override
    public void onFinish(Message message) {
        LogUtil.getInstance().d("TAG", "我看看这里面是什么玩意：" + message.obj.toString());
        handler.sendMessage(message);
        getActivity().unbindService(connection);
    }
}